use anyhow::Result;
use rbs::value;
use crate::models::contact::Contact;

pub struct ContactRepository;

impl ContactRepository {
    pub async fn init_table() -> Result<()> {
        crate::infra::database::rb()
            .exec(
                r#"
                CREATE TABLE IF NOT EXISTS contacts (
                    id TEXT PRIMARY KEY,
                    first_name TEXT,
                    last_name TEXT,
                    company TEXT,
                    job TEXT,
                    sip TEXT,
                    phone TEXT,
                    avatar TEXT
                )
                "#,
                vec![],
            )
            .await?;
        crate::infra::database::rb()
            .exec("CREATE INDEX IF NOT EXISTS idx_contacts_name ON contacts(last_name, first_name)", vec![])
            .await?;
        Ok(())
    }

    pub async fn list() -> Result<Vec<Contact>> {
        let list: Vec<Contact> = crate::infra::database::rb()
            .query_decode(
                "SELECT id, first_name, last_name, company, job, sip, phone, avatar FROM contacts ORDER BY last_name, first_name",
                vec![],
            )
            .await?;
        Ok(list)
    }

    pub async fn add(c: &Contact) -> Result<()> {
        crate::infra::database::rb()
            .exec(
                r#"INSERT OR REPLACE INTO contacts
                    (id, first_name, last_name, company, job, sip, phone, avatar)
                    VALUES(?,?,?,?,?,?,?,?)"#,
                vec![
                    value!(c.id.clone()),
                    value!(c.first_name.clone()),
                    value!(c.last_name.clone()),
                    value!(c.company.clone()),
                    value!(c.job.clone()),
                    value!(c.sip.clone()),
                    value!(c.phone.clone()),
                    value!(c.avatar.clone()),
                ],
            )
            .await?;
        Ok(())
    }
}


